package com.jumi.microservice.service.impl;


import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.jumi.microservice.common.constant.RedisKeyConstant;
import com.jumi.microservice.common.constant.RequestConstant;
import com.jumi.microservice.common.exception.BusinessException;
import com.jumi.microservice.common.redis.RedisCache;
import com.jumi.microservice.common.utils.ObjectUtils;
import com.jumi.microservice.config.ImAuthConfig;
import com.jumi.microservice.constant.*;
import com.jumi.microservice.domain.*;
import com.jumi.microservice.domain.dto.*;
import com.jumi.microservice.domain.vo.AccountQuery;
import com.jumi.microservice.domain.vo.LoginLogQuery;
import com.jumi.microservice.domain.vo.OperateLogQuery;
import com.jumi.microservice.mapper.*;
import com.jumi.microservice.service.AccountService;
import com.jumi.microservice.utils.OkHttpUtils;
import com.jumi.microservice.utils.SnowflakeIdWorker;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang3.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.DigestUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.Future;
import java.util.stream.Collectors;


/**
 * 账号管理service组件
 *
 * @author Administrator
 */
@Service
@Transactional(rollbackFor = Exception.class)
@RefreshScope
public class AccountServiceImpl implements AccountService {

    /**
     * 账号管理mapper组件
     */
    @Autowired
    private AccountMapper accountMapper;

    /**
     * 账号角色关系管理模块mapper组件
     */
    @Autowired
    private AccountRoleRelationshipMapper accountRoleRelationshipMapper;

    /**
     * 部门管理mapper组件
     */
    @Autowired
    private DepartmentMapper departmentMapper;

    /**
     * 日志管理mapper组件
     */
    @Autowired
    private LogMapper logMapper;

    /**
     * 角色和权限的关系管理模块mapper组件
     */
    @Resource
    private RolePriorityRelationshipMapper rolePriorityRelationshipMapper;

    /**
     * 权限模块mapper组件
     */
    @Resource
    private PriorityMapper priorityMapper;

    /**
     * IM客服权限配置
     */
    @Resource
    private ImAuthConfig imAuthConfig;

    @Value("${customer.register}")
    private String register;

    @Value("${customer.editRegister}")
    private String editRegister;

    @Value("${customer.emptyService}")
    private String emptyService;
    /**
     * 角色管理mapper组件
     */
    @Autowired
    private RoleMapper roleMapper;

    @Autowired
    private RedisCache redisCache;

    /**
     * 分页查询账号
     *
     * @param accountQuery 前端账号查询条件
     * @return 账号集合
     */
    @Override
    public List<AccountDTO> listAccountByPage(AccountQuery accountQuery) {
        ExceptionEnum.FAIL_NULL.doThrowIf(accountQuery == null);

        Long departmentId = accountQuery.getDepartmentId();
        LambdaQueryWrapper<Account> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Account::getIsDel, StatusEnum.STATUS_NO.getCode());
        // wrapper.eq(departmentId != null && departmentId != 1, Account::getDepartmentId, departmentId);
        wrapper.eq(accountQuery.getStatus() != null, Account::getStatus, accountQuery.getStatus());

        if (StringUtils.isNotEmpty(accountQuery.getUserAccount())) {
            wrapper.like(Account::getUserAccount, accountQuery.getUserAccount().trim());
        }

        if (StringUtils.isNotEmpty(accountQuery.getUserName())) {
            wrapper.like(Account::getUserName, accountQuery.getUserName().trim());
        }

        wrapper.ge(StringUtils.isNotEmpty(accountQuery.getCreateTimeFrom()), Account::getCreateTime, accountQuery.getCreateTimeFrom());
        wrapper.le(StringUtils.isNotEmpty(accountQuery.getCreateTimeTo()), Account::getCreateTime, accountQuery.getCreateTimeTo());
        wrapper.ge(StringUtils.isNotEmpty(accountQuery.getUpdateTimeFrom()), Account::getUpdateTime, accountQuery.getUpdateTimeFrom());
        wrapper.le(StringUtils.isNotEmpty(accountQuery.getUpdateTimeTo()), Account::getUpdateTime, accountQuery.getUpdateTimeTo());
        wrapper.orderByDesc(Account::getId, Account::getUpdateTime);

        if (departmentId != null) {
            List<Long> sonDepartment = departmentMapper.getSonDepartment(departmentId);
            sonDepartment.add(departmentId);
            wrapper.in(Account::getDepartmentId, sonDepartment);
        }

        List<Account> accounts = accountMapper.selectList(wrapper);
        List<AccountDTO> accountDtoList = convertAccountDoList2DtoList(accounts);

        Iterator<AccountDTO> iterator = accountDtoList.iterator();
        while (iterator.hasNext()) {
            AccountDTO accountDto = iterator.next();
            accountDto.setPassword(null);
            StringBuilder stringBuilder = new StringBuilder();
            String departmentName = getDepartmentName(accountDto.getDepartmentId(), stringBuilder);
            accountDto.setDepartmentName(departmentName);
            accountDto.setRoleName(accountRoleRelationshipMapper.getRoleNameByAccountId(accountDto.getUid()));

            if (!StringUtils.isBlank(accountQuery.getRoleName())) {
                if (!StringUtils.isBlank(accountDto.getRoleName())) {
                    if (!accountDto.getRoleName().contains(accountQuery.getRoleName().trim())) {
                        iterator.remove();
                    }
                } else {
                    iterator.remove();
                }
            }
            AccountLogin accountLogin = logMapper.getLoginNumAndLastLoginTimeByAccountId(accountDto.getUid());
            accountDto.setLoginNum(accountLogin.getLoginNum());
            accountDto.setLastLoginTime(accountLogin.getLastLoginTime());
        }
        return accountDtoList;
    }

    /**
     * 根据部门ID递归查询父部门名称和自己部门名称的拼串
     *
     * @param id 部门ID
     * @return 部门名称的拼串
     */
    private String getDepartmentName(Long id, StringBuilder stringBuilder) {
        Department department = departmentMapper.selectById(id);

        if (stringBuilder.length() == 0) {
            if (Objects.nonNull(department)) {
                stringBuilder.append(department.getDepartmentName());
            }
        } else {
            if (department.getParentId() != 0) {
                stringBuilder.insert(0, department.getDepartmentName() + "-");
            }
        }
        if (department.getParentId() != 0) {
            getDepartmentName(department.getParentId(), stringBuilder);
        }
        return stringBuilder.toString();
    }

    /**
     * 根据账号id查询账号
     *
     * @param id 账号id
     * @return 账号
     */
    @Override
    public AccountDTO getAccountById(Long id) {
        ExceptionEnum.FAIL_ID_NULL.doThrowIf(id == null);

        Account account = accountMapper.selectById(id);
        ExceptionEnum.FAIL_NULL.doThrowIf(account == null);

        AccountDTO accountDTO = convertAccountDo2Dto(account);
        accountDTO.setPassword(null);

        LambdaQueryWrapper<AccountRoleRelationship> accountRoleRelationshipQueryWrapper = Wrappers.lambdaQuery();
        accountRoleRelationshipQueryWrapper.eq(AccountRoleRelationship::getAccountId, accountDTO.getUid());
        AccountRoleRelationship accountRoleRelationship = accountRoleRelationshipMapper.selectOne(accountRoleRelationshipQueryWrapper);

        if (Objects.nonNull(accountRoleRelationship)) {
            Role role = roleMapper.selectById(accountRoleRelationship.getRoleId());

            if (Objects.nonNull(role)) {
                UserRoleDTO userRoleDTO = new UserRoleDTO();
                userRoleDTO.setRoleId(role.getId());
                userRoleDTO.setRoleName(role.getRoleName());
                accountDTO.setRoleRelations(userRoleDTO);
            }
        }
        return accountDTO;
    }

    @Override
    public AccountDTO getAccountByUid(Long uid) {
        ExceptionEnum.FAIL_ID_NULL.doThrowIf(uid == null);

        LambdaQueryWrapper<Account> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(Account::getStatus, StatusEnum.STATUS_YES.getCode());
        wrapper.eq(Account::getIsDel, StatusEnum.STATUS_NO.getCode());
        wrapper.eq(Account::getUid, uid);
        Account account = accountMapper.selectOne(wrapper);

        ExceptionEnum.FAIL_NULL.doThrowIf(account == null);

        AccountDTO accountDTO = convertAccountDo2Dto(account);

        return accountDTO;
    }

    /**
     * 新增账号
     *
     * @param account 账号
     */
    @Override
    public void saveAccount(AccountDTO account, HttpServletRequest request) {
        ExceptionEnum.FAIL_NULL.doThrowIf(account == null);
        checkAccount(account);
        Account accountDO = convertAccountDto2Do(account);

        SnowflakeIdWorker snowflakeIdWorker = new SnowflakeIdWorker(1, 1);
        Long uid = snowflakeIdWorker.nextId();
        accountDO.setUid(uid);

        if (!StringUtils.isBlank(accountDO.getPassword())) {
            String salt = generateSalt();
            String password = DigestUtils.md5DigestAsHex(accountDO.getPassword().concat(salt).getBytes());
            accountDO.setSalt(salt);
            accountDO.setPassword(password);
        }
        ExceptionEnum.FAIL_UID_NULL.doThrowIf(request.getHeader(RequestConstant.ADMIN_NAME) == null);

        LocalDateTime localDateTime = LocalDateTime.now();
        accountDO.setCreateTime(localDateTime);
        accountDO.setUpdateTime(localDateTime);
        accountDO.setCreater(request.getHeader(RequestConstant.ADMIN_NAME));
        accountDO.setModifier(request.getHeader(RequestConstant.ADMIN_NAME));

        int count = accountMapper.insert(accountDO);

        if (count != NumberConstant.NUMBER_ZERO.intValue()) {
            account.setId(accountDO.getId());
            account.setUid(accountDO.getUid());

            AccountRoleRelationship accountRoleRelationship = new AccountRoleRelationship();
            accountRoleRelationship.setAccountId(account.getUid());
            accountRoleRelationship.setRoleId(account.getRoleRelations().getRoleId());
            accountRoleRelationship.setCreateTime(localDateTime);
            accountRoleRelationship.setUpdateTime(localDateTime);
            accountRoleRelationshipMapper.insert(accountRoleRelationship);
            //判断当前用户的角色是否有客服权限
            int isService = service(account.getRoleRelations().getRoleId());
            //异步调用客服系统注册用户
            JSONObject json = new JSONObject();
            json.put(AccountConstant.USER_UID, accountDO.getUid());
            json.put(AccountConstant.USER_ACCOUNT, accountDO.getUserAccount());
            json.put(AccountConstant.USER_NAME, accountDO.getUserName());
            json.put(AccountConstant.USER_MOBILE, accountDO.getMobile());
            json.put(AccountConstant.IS_SERVICE,String.valueOf(isService));
            Future<Boolean> booleanFuture = OkHttpUtils.remoteCallCustomerService(register, String.valueOf(json));
            System.out.println(booleanFuture.isDone());
        }
    }

    /**
     * 判断当前用户的角色是否有客服权限
     * @param roleId
     * @return
     */
    private int service(Long roleId){
        LambdaQueryWrapper<RolePriorityRelationship> rolePriorityRelationshipQueryWrapper = Wrappers.lambdaQuery();
        rolePriorityRelationshipQueryWrapper.eq(RolePriorityRelationship::getRoleId, roleId);
        rolePriorityRelationshipQueryWrapper.eq(RolePriorityRelationship::getPriorityId, imAuthConfig.getAuthId());
        int count = rolePriorityRelationshipMapper.selectCount(rolePriorityRelationshipQueryWrapper);
        if(count <= 0){
            return 0;
        }
        return 1;
    }

    /**
     * 随即生成盐
     *
     * @return salt 盐
     */
    private String generateSalt() {
        return RandomStringUtils.randomAlphanumeric(20);
    }

    /**
     * 更新账号
     *
     * @param account 账号
     */
    @Override
    public void updateAccount(AccountDTO account, HttpServletRequest request) {
        ExceptionEnum.FAIL_NULL.doThrowIf(account == null || account.getId() == null);
        checkAccount(account);
        Account accountDO = convertAccountDto2Do(account);

        if (!StringUtils.isBlank(accountDO.getPassword())) {
            String salt = generateSalt();
            String password = DigestUtils.md5DigestAsHex(accountDO.getPassword().concat(salt).getBytes());
            accountDO.setSalt(salt);
            accountDO.setPassword(password);
        }

        LocalDateTime localDateTime = LocalDateTime.now();
        ExceptionEnum.FAIL_UID_NULL.doThrowIf(request.getHeader(RequestConstant.ADMIN_NAME) == null);
        accountDO.setModifier(request.getHeader(RequestConstant.ADMIN_NAME));
        accountDO.setUpdateTime(localDateTime);

        int count = accountMapper.updateById(accountDO);
        accountDO.setUid(accountMapper.selectById(accountDO.getId()).getUid());
        account.setUid(accountDO.getUid());
        if (count != NumberConstant.NUMBER_ZERO.intValue()) {
            Long roleRelations = account.getRoleRelations().getRoleId();

            if (Objects.nonNull(roleRelations)) {
                LambdaUpdateWrapper<AccountRoleRelationship> updateWrapper = new LambdaUpdateWrapper<>();
                updateWrapper.set(AccountRoleRelationship::getRoleId, roleRelations)
                        .set(AccountRoleRelationship::getUpdateTime, localDateTime)
                        .eq(AccountRoleRelationship::getAccountId, account.getUid());
                accountRoleRelationshipMapper.update(new AccountRoleRelationship(), updateWrapper);
            }
            //判断当前用户的角色是否有客服权限
            int isService = service(account.getRoleRelations().getRoleId());
            //异步调用客服系统注册用户
            JSONObject json = new JSONObject();
            json.put(AccountConstant.USER_UID, accountDO.getUid());
            json.put(AccountConstant.USER_ACCOUNT, accountDO.getUserAccount());
            json.put(AccountConstant.USER_NAME, accountDO.getUserName());
            json.put(AccountConstant.USER_MOBILE, accountDO.getMobile());
            json.put(AccountConstant.IS_SERVICE,String.valueOf(isService));
            Future<Boolean> booleanFuture = OkHttpUtils.remoteCallCustomerService(editRegister, String.valueOf(json));
            System.out.println(booleanFuture.isDone());
        }
    }

    private void checkAccount(AccountDTO account) {
        List<Object> accountIdList = accountMapper.selectObjs(
                Wrappers.<Account>lambdaQuery()
                        .select(Account::getId)
                        .eq(Account::getUserAccount, account.getUserAccount())
                        .eq(Account::getIsDel, StatusEnum.STATUS_NO.getCode())
                        .ne(account.getId() != null, Account::getId, account.getId()));

        if (accountIdList.size() > NumberConstant.NUMBER_ZERO.intValue()) {
            throw new BusinessException(UserAccountEnum.USER_HAS_EXISTED);
        }

        List<Object> objectList = accountMapper.selectObjs(
                Wrappers.<Account>lambdaQuery()
                        .select(Account::getId)
                        .eq(Account::getMobile, account.getMobile())
                        .eq(Account::getIsDel, StatusEnum.STATUS_NO.getCode())
                        .ne(account.getId() != null, Account::getId, account.getId()));

        if (objectList.size() > NumberConstant.NUMBER_ZERO.intValue()) {
            throw new BusinessException(UserAccountEnum.PHONE_HAS_EXISTED);
        }
    }

    /**
     * 删除账号
     *
     * @param ids 账号ids,支持批量删除,账号ID以逗号分割
     */
    @Override
    public void removeAccountById(String ids, HttpServletRequest request) {
        List<Account> accounts = accountMapper.selectList(
                Wrappers.<Account>lambdaQuery()
                        .select(Account::getStatus)
                        .eq(Account::getIsDel, StatusEnum.STATUS_NO.getCode())
                        .apply("id in (" + ids + ")"));

        for (Account account : accounts) {
            if (account.getStatus().equals(StatusEnum.STATUS_YES.getCode())) {
                throw new BusinessException(UserAccountEnum.USER_STATUS_ABLED);
            }
        }
        ExceptionEnum.FAIL_UID_NULL.doThrowIf(request.getHeader(RequestConstant.ADMIN_NAME) == null);

        LambdaUpdateWrapper<Account> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(Account::getIsDel, StatusEnum.STATUS_YES.getCode())
                .set(Account::getUpdateTime, LocalDateTime.now())
                .set(Account::getModifier, request.getHeader(RequestConstant.ADMIN_NAME))
                .in(Account::getId, Arrays.asList(ids.split(",")));
        int update = accountMapper.update(new Account(), updateWrapper);
        //删除用户的绑定角色关系
        if (CollectionUtil.isNotEmpty(accounts)) {
            accountRoleRelationshipMapper.delete(
                    Wrappers.<AccountRoleRelationship>lambdaQuery()
                            .in(AccountRoleRelationship::getAccountId, accounts.stream().map(Account::getUid).collect(Collectors.toList())));
        }

        if (update > NumberConstant.NUMBER_ZERO.intValue()) {
            JSONObject json = new JSONObject();
            json.put(AccountConstant.USER_UID, ids);
            Future<Boolean> booleanFuture = OkHttpUtils.remoteCallCustomerService(emptyService, String.valueOf(json));
        }
    }

    /**
     * 账号状态启用/停用
     *
     * @param id     主键id
     * @param status 状态 (1启用，0.禁用)
     */
    @Override
    public void enableStatus(Long id, Integer status, HttpServletRequest request) {
        Account account = accountMapper.selectById(id);
        ExceptionEnum.FAIL_NULL.doThrowIf(account == null);

        ExceptionEnum.FAIL_UID_NULL.doThrowIf(request.getHeader(RequestConstant.ADMIN_NAME) == null);

        account.setStatus(status);
        account.setModifier(request.getHeader(RequestConstant.ADMIN_NAME));
        account.setUpdateTime(LocalDateTime.now());
        int update = accountMapper.updateById(account);

        if (status.equals(NumberConstant.NUMBER_ZERO.intValue())) {
            String key = RedisKeyConstant.USER_TOKEN_KEY + account.getUid();
            redisCache.deleteObject(key);
        }

        if (update > NumberConstant.NUMBER_ZERO.intValue() && status.equals(NumberConstant.NUMBER_ZERO.intValue())) {
            JSONObject json = new JSONObject();
            json.put(AccountConstant.USER_UID, account.getUid());
            Future<Boolean> booleanFuture = OkHttpUtils.remoteCallCustomerService(emptyService, String.valueOf(json));
        }
    }


    /**
     * 登录日次数志分页查询
     *
     * @param loginLogQuery 查询条件
     * @return LoginLogDTO 登录日志DTO列表
     */
    @Override
    public List<LoginLogDTO> listAccountLoginByPage(LoginLogQuery loginLogQuery) {
        ExceptionEnum.FAIL_NULL.doThrowIf(loginLogQuery == null);

        LambdaQueryWrapper<Log> wrapper = Wrappers.lambdaQuery();

        if (loginLogQuery.getAccountId() != null) {
            Account account = accountMapper.selectById(loginLogQuery.getAccountId());
            wrapper.eq(Log::getAccountId, account.getUid());
        }

        wrapper.eq(Log::getIsDel, StatusEnum.STATUS_NO.getCode());
        wrapper.eq(Log::getOperateType, LogOperationTypeEnum.OPERATION_LOGIN.getCode());
        wrapper.ge(StringUtils.isNotEmpty(loginLogQuery.getOperateTimeFrom()), Log::getOperateTime, loginLogQuery.getOperateTimeFrom());
        wrapper.le(StringUtils.isNotEmpty(loginLogQuery.getOperateTimeTo()), Log::getOperateTime, loginLogQuery.getOperateTimeTo());
        wrapper.orderByDesc(Log::getOperateTime);

        List<LoginLogDTO> accountDtoList = convertAccountLogDoList2DtoList(logMapper.selectList(wrapper));
        return accountDtoList;
    }

    /**
     * 操作日志分页查询
     *
     * @param operateLogQuery 查询条件
     * @return LoginLogDTO 登录日志DTO列表
     */
    @Override
    public List<LogDTO> listAccountOperateLogByPage(OperateLogQuery operateLogQuery) {
        ExceptionEnum.FAIL_NULL.doThrowIf(operateLogQuery == null);

        LambdaQueryWrapper<Log> wrapper = Wrappers.lambdaQuery();

        if (operateLogQuery.getAccountId() != null) {
            Account account = accountMapper.selectById(operateLogQuery.getAccountId());
            wrapper.eq(Log::getAccountId, account.getUid());
        }

        wrapper.eq(Log::getIsDel, StatusEnum.STATUS_NO.getCode());
        wrapper.like(StringUtils.isNotEmpty(operateLogQuery.getDepartmentName()), Log::getDepartmentName, operateLogQuery.getDepartmentName());
        wrapper.like(StringUtils.isNotEmpty(operateLogQuery.getUserName()), Log::getUserName, operateLogQuery.getUserName());
        wrapper.like(StringUtils.isNotEmpty(operateLogQuery.getMobile()), Log::getMobile, operateLogQuery.getMobile());
        wrapper.eq(operateLogQuery.getLogOperationType() != null, Log::getOperateType, operateLogQuery.getLogOperationType());
        wrapper.like(StringUtils.isNotEmpty(operateLogQuery.getAction()), Log::getOperateAction, operateLogQuery.getAction());
        wrapper.ge(StringUtils.isNotEmpty(operateLogQuery.getOperateTimeFrom()), Log::getOperateTime, operateLogQuery.getOperateTimeFrom());
        wrapper.le(StringUtils.isNotEmpty(operateLogQuery.getOperateTimeTo()), Log::getOperateTime, operateLogQuery.getOperateTimeTo());
        wrapper.orderByDesc(Log::getOperateTime);

        List<LogDTO> operateLogDtoList = convertOperateLogDoList2DtoList(logMapper.selectList(wrapper));
        return operateLogDtoList;
    }

    @Override
    public String listImPriority(Long adminID) {
        //根据配置文件种的客服id获取客服权限下的所有数据id
        List<PriorityCheckPo> priorityCheckPos = priorityMapper.selectAllChildList(imAuthConfig.getAuthId());
        if (priorityCheckPos.isEmpty()) {
            return "";
        }
        List<Integer> priorityIdList = new ArrayList<>();
        for (PriorityCheckPo po : priorityCheckPos) {
            priorityIdList.add(po.getMenu_id());
        }

        //根据用户id查询账号和角色的关系表-取得角色主键ID
        QueryWrapper<AccountRoleRelationship> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account_id", adminID);
        queryWrapper.select("account_id,role_id");
        AccountRoleRelationship accountRoleRelationship = accountRoleRelationshipMapper.selectOne(queryWrapper);
        if (accountRoleRelationship == null) {
            return "";
        }
        //根据角色主键ID查询角色和权限的关系表-取得权限主键ID
        QueryWrapper<RolePriorityRelationship> queryWrapper1 = new QueryWrapper<>();
        queryWrapper1.eq("role_id", accountRoleRelationship.getRoleId());
        queryWrapper1.in("priority_id", priorityIdList);
        queryWrapper1.select("role_id,priority_id");
        List<RolePriorityRelationship> rolePriorityRelationship = rolePriorityRelationshipMapper.selectList(queryWrapper1);
        if (rolePriorityRelationship.isEmpty()) {
            return "";
        }

        List<Integer> priorityIdList2 = new ArrayList<>();
        for (RolePriorityRelationship relationship : rolePriorityRelationship) {
            priorityIdList2.add(relationship.getPriorityId());
        }
        //根据权限主键ID查询权限表
        QueryWrapper<Priority> queryWrapper2 = new QueryWrapper<>();
        queryWrapper2.in("id", priorityIdList2);
        queryWrapper2.eq("is_del", StatusEnum.STATUS_NO.getCode());
        queryWrapper2.select("priority_code");
        List<Priority> list = priorityMapper.selectList(queryWrapper2);

        List<String> auth = new ArrayList<>(list.size());

        for (Priority pr : list) {
            auth.add(pr.getPriorityCode());
        }

        return StringUtils.join(auth, ",");
    }


    /**
     * 将账号DTO对象转换为DO对象
     *
     * @param accountDTO 账号DTO
     * @return Account 账号DO
     */
    private Account convertAccountDto2Do(AccountDTO accountDTO) {
        Account account = null;
        try {
            account = accountDTO.clone(Account.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return account;
    }

    /**
     * 将账号DO对象转换为DTO对象
     *
     * @param account 账号DO
     * @return AccountDTO 账号DTO
     */
    private AccountDTO convertAccountDo2Dto(Account account) {
        AccountDTO accountDTO = null;
        try {
            accountDTO = account.clone(AccountDTO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return accountDTO;
    }


    /**
     * 将账号DO对象集合转换为DTO对象集合
     *
     * @param accounts 账号DO集合
     * @return List<AccountDTO> 账号DTO对象集合
     */
    private List<AccountDTO> convertAccountDoList2DtoList(List<Account> accounts) {
        List<AccountDTO> accountDtoList = null;
        try {
            accountDtoList = ObjectUtils.convertList(accounts, AccountDTO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return accountDtoList;
    }

    /**
     * 将登录次数日志DO对象集合转换为DTO对象集合
     *
     * @param logs 账号登录日志DO 集合
     * @return List<LoginLogDTO> 账号登录日志DTO对象集合
     */
    private List<LoginLogDTO> convertAccountLogDoList2DtoList(List<Log> logs) {
        List<LoginLogDTO> loginLogDtoList = null;
        try {
            loginLogDtoList = ObjectUtils.convertList(logs, LoginLogDTO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return loginLogDtoList;
    }

    /**
     * 将操作日志DO对象集合转换为DTO对象集合
     *
     * @param logs 账号登录日志DO 集合
     * @return List<LogDTO> 账号登录日志DTO对象集合
     */
    private List<LogDTO> convertOperateLogDoList2DtoList(List<Log> logs) {
        List<LogDTO> logDtoList = null;
        try {
            logDtoList = ObjectUtils.convertList(logs, LogDTO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return logDtoList;
    }

    /**
     * 将权限表DO对象集合转换为DTO对象集合
     *
     * @param priority
     * @return
     */
    private List<PriorityDTO> convertPriorityDoList2DtoList(List<Priority> priority) {
        List<PriorityDTO> dtosList = null;
        try {
            dtosList = ObjectUtils.convertList(priority, PriorityDTO.class);
        } catch (Exception e) {
            ExceptionEnum.FAIL_CHANGE.newException();
        }
        return dtosList;
    }
}
